<?php

/**
 * Class TcpClient
 */
class TcpClient {

    private $client;

    public function __construct()
    {
        $this->client = new Swoole\Client(SWOOLE_SOCK_TCP);
    }

    public function connect($post = 9501) {
        if (!$this->client->connect('127.0.0.1', $post, -1)) {
            exit("connect failed. Error: {$this->client->errCode}\n");
        }
    }

    /**
     * @param $data
     */
    public function send($data = []) {
        $data = [
            'method' => 'send',
            'data' => [
                'name' => 'hello',
                'from' => 'tcp-client'
            ]
        ];
        $data = json_encode($data);
        //拼接"\r\n"，是解决在循环场景下，投递任务可能会出现的tcp粘包问题。
        $this->client->send($data . "\r\n");
        $this->client->close();
    }

    /**
     * 接收数据
     * @return array
     */
    public function recv()
    {
        return $this->client->recv();
    }
}

$client = new TcpClient();
$client->connect();
$client->send();